home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 595 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: news.iag.net!news
  2. From: jatmon@iag.net (John R Buchan)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: gets() question
  5. Date: 7 Jan 1996 18:17:28 GMT
  6. Organization: Internet Access Group, Orlando, Florida
  7. Message-ID: <4cp2no$h9l@news.iag.net>
  8. References: <4cosgf$rir@newsbf02.news.aol.com>
  9. NNTP-Posting-Host: pm3-orl11.iag.net
  10. X-Newsreader: WinVN 0.99.7
  11.  
  12. In article <4cosgf$rir@newsbf02.news.aol.com>, simpsondg@aol.com says...
  13. <snip>
  14. >#include "stdio.h"
  15. >
  16. >void main(void)
  17. >{
  18. >   int i[5];
  19. >   char s[3][10];
  20. >
  21. >   printf ("Enter s[0]:  ");
  22. >   gets (s[0]);
  23. >
  24. >   printf ("Enter i[0]]:  ");
  25. >   scanf ("%d",&i[0]);
  26. >
  27. >   printf ("Enter s[1]:  ");
  28. >   gets (s[1]);                  /* this gets() doesn't wait for input */
  29. >
  30. >   printf ("Enter i[1]]:  ");
  31. >   scanf ("%d",&i[1]);
  32. >}
  33.  
  34. This is one of the side effects of scanf that is explained in the c.l.c faq
  35. (Frequently Asked Question) list.  The list is available for anonymous ftp
  36. from rtfm.mit.edu /pub/usenet/comp.lang.c.
  37.  
  38. Basically, when scanf is used to input numbers (and few other circumstances)
  39. it stops reading when it reaches the first char that doesn't fit its
  40. conversion type. Since '\n' isn't in the list of acceptable chars for an
  41. int ("%d"), scanf stops reading and leaves it on the stream.  When the next
  42. gets is executed, it will stop reading with the first '\n', which is the one
  43. left behind by the scanf.  So, it isn't actually skipped over, it just reads 
  44. a blank line.
  45.  
  46. As a general rule it is safer and easier to use fgets for any user input, 
  47. instead of gets or scanf.  If you are reading a string, remember that fgets 
  48. leaves the '\n' attached.  For any other input fgets it to a buffer and
  49. use sscanf, strtok, etc to parse the buffer.
  50.  
  51. -- 
  52. John R Buchan           -:|:-     Looking for that elusive FAQ?  ftp to:
  53. jatmon@mail.iag.net     -:|:-     rtfm.mit.edu /pub/usenet-by-group/....
  54.  
  55.